<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class User extends Controller
{
    use \App\Traits\UserTrait, \App\Traits\CacheTrait, \App\Traits\CompanyTrait, \App\Traits\AjaxTrait, \App\Traits\SessionTrait, \App\Traits\DbTrait, \App\Traits\ErrorTrait;

    /**
     * 用户登录
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function userLogin(Request $request)
    {
        $postData = $this->ajaxUserLogin($request);
        $result = $this->userLoginTrait(parent::CODE_USER_LOGIN, $postData);
        if ($result) {
            $this->sessionUserLogin($result);
            echo json_encode(['result' => 0]);
        } else {
            echo json_encode(['result' => -1, 'msg' => '用户名或密码错误']);
        }
    }

    /**
     * 用户通过短信登录，如果用户不存在，则默认创建一个
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function userLoginBySms(Request $request)
    {
        $postData = $this->ajaxUserLoginBySms($request);
        $codeStatus = $this->checkSmsExistTrait($postData);
        if (!$codeStatus) {
            echo json_encode($this->codeOrPhoneNotExistError());
            exit;
        }

        $result = $this->checkUserExitsTrait(parent::CODE_CHECK_USER_EXIST, $postData);
        if ($result) {
            //用户已经存在，跳转登录到后台
            $userBaseInfo = $this->getUserBaseInfoTrait(parent::CODE_GET_USER_INFO, ['phone' => $postData['phone']]);
            $this->sessionUserCECIFF();
            $this->sessionUserLogin($userBaseInfo);
            echo json_encode($this->redirectUserAdminSuccesss());
        }
        //用户不存在
        else {
            $registData = [
                'phone' => $postData['phone'],
                'pwd' => '12345678a',
                'from' => '',
            ];
            $registResult = $this->userRegistTrait(parent::CODE_USER_REGIST, $registData);
            if ($registResult) {
                $userBaseInfo = $this->getUserBaseInfoTrait(parent::CODE_GET_USER_INFO, ['phone' => $postData['phone']]);
                $this->sessionUserLogin($userBaseInfo);
            }
            $this->sessionUserCECIFF();
            echo $registResult ? json_encode($this->normalSuccess()) : json_encode($this->userRegistError());
        }

    }

    /**
     * 用户注册
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function userRegist(Request $request)
    {
        $postData = $this->ajaxUserRegist($request);
        $result = $this->userRegistTrait(parent::CODE_USER_REGIST, $postData);
        echo $result ? json_encode(['result' => 0]) : json_encode(['result' => -1]);
    }

    /**
     * 用户退出
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function userLogout(Request $request)
    {
        $this->sessionUserLogout($request);
        return redirect('/');
    }

    /**
     * 用户忘记密码
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function userForgetPwd(Request $request)
    {
        $postData = $this->ajaxUserForgetPwd($request);
        $result = $this->userForgetPwdTrait(parent::CODE_UPDATE_USER_PWD, $postData);
        echo $result ? json_encode(['result' => 0]) : json_encode(['result' => -1]);
    }

    /**
     * 基础信息
     * @return [type] [description]
     */
    public function account()
    {
        $data = [
            'phone' => $this->sessionReturnUserPhone(),
        ];
        $result = $this->getUserBaseInfoTrait(parent::CODE_GET_USER_INFO, $data);
        $areaNameList = $this->getAreaNameList();
        $provinceList = $this->cacheGetProvinceList();
        $areaList = $this->cacheGetAreaList();

        $result = $result ? $result : [];

        $viewData = [
            'select_info' => 'account',
            'account_info' => @$result['account_info'],
            'province_list' => $provinceList,
            'p' => '',
            'c' => '',
            'a' => '',
            'address' => '',
        ];

        if ($result) {
            $accountInfo = $result['account_info'];
            if ($accountInfo['address']['p'] && $accountInfo['address']['c'] && $accountInfo['address']['a']) {
                $viewData['p'] = $accountInfo['address']['p'];
                $viewData['c'] = $accountInfo['address']['c'];
                $viewData['a'] = $accountInfo['address']['a'];
                $viewData['address'] = $accountInfo['address']['d'];
                $viewData['city_list'] = $areaList[$accountInfo['address']['p']];
                $viewData['area_list'] = $areaList[$accountInfo['address']['c']];
                $viewData['getNameList'] = $areaNameList;
                $viewData['account_info']['contact_phone'] = $accountInfo['contact_phone'];
                $viewData['account_info']['email'] = $accountInfo['email'];
            }
        }
        return view('admin/user/account_info', $viewData);
    }

    /**
     * 公司信息
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function companyInfo(Request $request)
    {
        $type = $request->input('type', 1);
        $data = [
            'company_id' => $this->sessionReturnCompanyId(),
        ];
        $result = $this->getCompanyInfo(parent::CODE_GET_COMPANY_INFO, $data);
        $result = $result ? $result : [];
        if ($result && $result['type'] != 0) {
            if (@$result['type'] == 1) {
                $viewData = $this->_returnServicerViewData($result);
                return view('admin/user/servicer/view', $viewData);
            } else if (@$result['type'] == 2) {
                $viewData = $this->_returnAuthorViewData($result);
                return view('admin/user/proprietor/view', $viewData);
            } else {
                return $this->_servicerInfo();
            }
        } else {
            if ($type == 1) {
                return $this->_servicerInfo();
            } else if ($type == 2) {
                return $this->_proprietor();
            } else {
                return $this->_servicerInfo();
            }
        }
    }

    private function _returnServicerViewData($result)
    {
        $provinceList = $this->cacheGetProvinceList();
        $areaNameList = $this->getAreaNameList();
        $otherDicList = $this->cacheGetOtherDicList();
        $otherNameList = $this->cacheGetOtherDicNameList();
        $domainList = $otherDicList[config('constant.domain_dic')][0];
        $domainList2 = $otherDicList[config('constant.domain_dic')][$domainList[0]['id']];
        $serviceDomainList = $otherDicList[config('constant.service_domain_dic')][0];
        $methodList = $otherDicList[config('constant.method_dic')][0];

        $bankLevelList = config('constant.bank_level_list');
        $serviceTypeList = config('constant.domain_service_type');
        $companyTypeList = config('constant.needle_project_owner_type');

        list($p, $c, $a) = explode(',', $result['company_regist_address_id']);
        list($p1, $c1, $a1) = explode(',', $result['contact_user_address_id']);
        $cityList = $this->cacheGetProvinceList($p);
        $areaList = $this->cacheGetProvinceList($c);
        $cityList1 = $this->cacheGetProvinceList($p1);
        $areaList1 = $this->cacheGetProvinceList($c1);

        $techRouteInfo = [];
        if ($result['tech_route_info'] && $result['tech_route_info'] != '[]') {
            $arrTechRoute = json_decode($result['tech_route_info'], true);
            for ($i = 0; $i < count($arrTechRoute); $i++) {
                $techRouteInfo[$i]['name'] = $otherNameList[$arrTechRoute[$i]['id']]['name'];
                $techRouteInfo[$i]['flag'] = decbin($arrTechRoute[$i]['ab']);
            }
        }

        $viewData = [
            'province_list' => $provinceList,
            'domain1_list' => $domainList,
            'domain2_list' => $domainList2,
            'city_list' => $cityList,
            'area_list' => $areaList,
            'city_list1' => $cityList1,
            'area_list1' => $areaList1,
            'p' => $p,
            'c' => $c,
            'a' => $a,
            'p1' => $p1,
            'c1' => $c1,
            'a1' => $a1,
            'company_type_list' => $companyTypeList,
            'bank_level_list' => $bankLevelList,
            'service_type_list' => $serviceTypeList,
            'service_domain_list' => $serviceDomainList,
            'method_list' => $methodList,
            'dataInfo' => $result,
            'selectCompanyDomainList' => $result['company_domain_id'] ? explode(',', $result['company_domain_id']) : [],
            'selectServiceDomainList' => explode(',', $result['service_domain_id']),
            'selectMethodList' => explode(',', $result['method_id']),
            'getNameList' => $otherNameList,
            'getAreaNameList' => $areaNameList,
            'select_info' => 'company',
            'record_city_province_id' => '',
            'record_city_id' => '',
            'record_city_list' => [],
            'tech_route_info' => $techRouteInfo,
        ];
        if ($result['record_info']['city'] > 0) {
            $viewData['record_city_province_id'] = $areaNameList[$result['record_info']['city']]['parent_id'];
            $viewData['record_city_id'] = $result['record_info']['city'];
            $viewData['record_city_list'] = $areaDicList[$areaNameList[$result['record_info']['city']]['parent_id']];
        }

        return $viewData;
    }

    private function _servicerInfo()
    {
        $provinceList = $this->cacheGetProvinceList();
        $otherDicList = $this->cacheGetOtherDicList();
        $otherNameList = $this->cacheGetOtherDicNameList();
        $domainList = $otherDicList[config('constant.domain_dic')][0];
        $domainList2 = $otherDicList[config('constant.domain_dic')][$domainList[0]['id']];
        $serviceDomainList = $otherDicList[config('constant.service_domain_dic')][0];
        $methodList = $otherDicList[config('constant.method_dic')][0];

        $bankLevelList = config('constant.bank_level_list');
        $serviceTypeList = config('constant.domain_service_type');
        $companyTypeList = config('constant.needle_project_owner_type');

        $viewData = [
            'select_info' => 'company',
            'company_type_list' => $companyTypeList,
            'bank_level_list' => $bankLevelList,
            'province_list' => $provinceList,
            'domain1_list' => $domainList,
            'domain2_list' => $domainList2,
            'service_type_list' => $serviceTypeList,
            'service_domain_list' => $serviceDomainList,
            'method_list' => $methodList,
        ];
        return view('admin/user/servicer/add', $viewData);
    }

    private function _returnAuthorViewData($result)
    {
        $provinceList = $this->cacheGetProvinceList();
        $areaNameList = $this->getAreaNameList();

        $companyTypeList = config('constant.needle_project_owner_type');

        list($p, $c, $a) = explode(',', $result['company_regist_address_id']);
        list($p1, $c1, $a1) = explode(',', $result['contact_user_address_id']);
        $cityList = $this->cacheGetProvinceList($p);
        $areaList = $this->cacheGetProvinceList($c);
        $cityList1 = $this->cacheGetProvinceList($p1);
        $areaList1 = $this->cacheGetProvinceList($c1);
        $viewData = [
            'select_info' => 'company',
            'dataInfo' => $result,
            'province_list' => $provinceList,
            'city_list' => $cityList,
            'area_list' => $areaList,
            'city_list1' => $cityList1,
            'area_list1' => $areaList1,
            'p' => $p,
            'c' => $c,
            'a' => $a,
            'p1' => $p1,
            'c1' => $c1,
            'a1' => $a1,
            'company_type_list' => $companyTypeList,
            'getAreaNameList' => $areaNameList,
        ];
        return $viewData;
    }

    private function _proprietor()
    {
        $provinceList = $this->cacheGetProvinceList();
        $companyTypeList = config('constant.needle_project_owner_type');

        $viewData = [
            'select_info' => 'company',
            'company_type_list' => $companyTypeList,
            'province_list' => $provinceList,
        ];
        return view('admin/user/proprietor/add', $viewData);
    }

    /**
     * 公司信息修改页面
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function companyEdit(Request $request)
    {
        $type = $request->input('type');
        $data = [
            'company_id' => $this->sessionReturnCompanyId(),
        ];
        $result = $this->getCompanyInfo(parent::CODE_GET_COMPANY_INFO, $data);
        $result = $result ? $result : [];
        if ($result['type'] == $type) {
            if ($type == 1) {
                $viewData = $this->_returnServicerViewData($result);
                return view('admin/user/servicer/edit', $viewData);
            } else if ($type == 2) {
                $viewData = $this->_returnAuthorViewData($result);
                return view('admin/user/proprietor/edit', $viewData);
            }
        }

    }

    /**
     * 修改密码页面
     * @return [type] [description]
     */
    public function passwordInfo()
    {
        $accountPhoneInfo = $this->sessionReturnUserAccountInfo();
        $viewData = [
            'select_info' => 'password',
            'account_phone' => $accountPhoneInfo['user_phone'],
        ];
        return view('admin/user/password_info', $viewData);
    }

}
